<?php

namespace app\admin\model\cms;

use addons\cms\library\FulltextSearch;
use addons\cms\library\Service;
use app\admin\model\extend\Policy;
use app\common\model\User;
use think\Model;
use traits\model\SoftDelete;
use think\Db;

class Archives extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'cms_archives';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    protected $defaultSoftDelete = 0;
    // 追加属性
    protected $append = [
        'flag_text',
        'status_text',
        'publishtime_text',
        'url',
        'fullurl',
        'style_bold',
        'style_color',
    ];
    protected static $config = [];

    public function getUrlAttr($value, $data)
    {
        $diyname = isset($data['diyname']) && $data['diyname'] ? $data['diyname'] : $data['id'];
        $catename = isset($this->channel) && $this->channel ? $this->channel->diyname : 'all';
        $cateid = isset($this->channel) && $this->channel ? $this->channel->id : 0;
        return addon_url('cms/archives/index', [':id' => $data['id'], ':diyname' => $diyname, ':channel' => $data['channel_id'], ':catename' => $catename, ':cateid' => $cateid], static::$config['urlsuffix']);
    }

    public function getFullurlAttr($value, $data)
    {
        $diyname = isset($data['diyname']) && $data['diyname'] ? $data['diyname'] : $data['id'];
        $catename = isset($this->channel) && $this->channel ? $this->channel->diyname : 'all';
        $cateid = isset($this->channel) && $this->channel ? $this->channel->id : 0;
        return addon_url('cms/archives/index', [':id' => $data['id'], ':diyname' => $diyname, ':channel' => $data['channel_id'], ':catename' => $catename, ':cateid' => $cateid], static::$config['urlsuffix'], true);
    }

    public function getOriginData()
    {
        return $this->origin;
    }

    /**
     * 批量设置数据
     * @param $data
     * @return $this
     */
    public function setData($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }
        $this->data = array_merge($this->data, $data);
        return $this;
    }

    protected static function init()
    {

            self::$config = $config = get_addon_config('cms');
            self::beforeInsert(function ($row) {
                if (!isset($row['admin_id']) || !$row['admin_id']) {
                    $admin_id = session('admin.id');
                    $row['admin_id'] = $admin_id ? $admin_id : 0;
                }
            });
            self::afterInsert(function ($row) {
                $pk = $row->getPk();
                $channel = Channel::get($row['channel_id']);
                $row->getQuery()->where($pk, $row[$pk])->update(['model_id' => $channel ? $channel['model_id'] : 0]);
                Channel::where('id', $row['channel_id'])->setInc('items');

            });
            self::beforeWrite(function ($row) {
                $changedData = $row->getChangedData();
                if (isset($changedData['flag'])) {
                    $row['weigh'] = is_array($changedData['flag']) && in_array('top', $changedData['flag'])
                        ? ($row['weigh'] == 0 ? 9999 : $row['weigh'])
                        : ($row['weigh'] == 9999 ? 0 : $row['weigh']);
                }

                if (isset($row['content'])) {
                    $row['content'] = Service::autolinks($row['content']);
                }
                //在更新之前对数组进行处理
                foreach ($row->getData() as $k => $value) {
                    if (is_array($value) && is_array(reset($value))) {
                        $value = json_encode(self::getArrayData($value), JSON_UNESCAPED_UNICODE);
                    } else {
                        $value = is_array($value) ? implode(',', $value) : $value;
                    }
                    $row->$k = $value;
                }
            });
            self::afterWrite(function ($row) use ($config) {
                if (isset($row['channel_id'])) {
                    //在更新成功后刷新副表、TAGS表数据、栏目表
                    $channel = Channel::get($row->channel_id);
                    if ($channel) {
                        $model = Modelx::get($channel['model_id']);
                        if ($model && isset($row['content'])) {
                            $values = array_intersect_key($row->getData(), array_flip($model->fields));
                            $values['id'] = $row['id'];
                            $values['uid'] = $row['school_id'];
                            $values['content'] = $row['content'];
                            db($model['table'])->insert($values, true);
                            $flag=0;
                            $fit_channel=DB::name('cms_channel')->field('parent_id,fit_channel,list_type,p_type')->where(['id'=>$row['channel_id']])->find();
                            $province=explode(",",$values['province']); //插入省份表
                            if (strtolower(request()->action())=='add'){
                                if ($row['h_type']==1){
                                    if ($row['channel_id']==181) {
                                        //高考真题  转高考试卷栏目
                                        $con['catid'] = 89;
                                    }else{
                                        $con['catid'] = 69;
                                    }
                                }else{
                                    $isin = in_array("1",$province);
                                    $isin1 = in_array("3",$province);
                                    if ($isin || $isin1){
                                        if ($row['channel_id']==12){
                                            if ($isin){
                                                $con['catid']=126;
                                            }else{
                                                $con['catid']=27;
                                            }
                                        }else{
                                            $con['catid']=$fit_channel['fit_channel'];
                                        }
                                    }else{
                                        $con['catid']=0;
                                    }
//                                    if ($fit_channel['list_type']!=3 && $con['catid']){
//                                        $flag=1;
//                                         $h_uid=DB::name('school_z')->field('h_uid')->where(['id'=>$row['school_id']])->find()['h_uid'];
//                                    }
                                }
                                if ($con['catid']>0 && $fit_channel['list_type']!=3){
                                    $con['title']=$row['title'];
                                    $con['status']=99;
                                    $con['username']='gkzzd';
                                    $con['adminid']=1;
                                    $con['inputtime']=time();
                                    $con['updatetime']=time();
                                    $con['istu']=1;
                                    $h_uid=DB::name('school_z')->field('h_uid')->where(['id'=>$row['school_id']])->find()['h_uid'];

                                    $con['uid']=$h_uid?$h_uid:0;
                                    $con['keywords']=isset($row['keywords'])?$row['keywords']:'';
                                    $con['description']=isset($row['description'])?$row['description']:'';
                                    $con['zd_id']=$row['id'];
//                                    if ($flag==1){
//                                        if ($con['uid']){
//                                            $h_id=Db::connect("database_art")->table("h_article")->insertGetId($con);
//                                        }else{
//                                            $h_id='';
//                                        }
//                                    }else{
//                                        $h_id=Db::connect("database_art")->table("h_article")->insertGetId($con);
//                                    }
                                    $h_id=Db::connect("database_art")->table("h_article")->insertGetId($con);
                                    if ($h_id){
                                        DB::name('cms_archives')->where(['id'=>$row['id']])->update(['h_id'=>$h_id]);
                                        $h_data['copyfrom']=isset($row['source'])?$row['source']:'';
                                        $h_data['id']=$h_id;
                                        $h_data['maxcharperpage']=10000;
                                        $h_data['paginationtype']=2;
                                        $h_data['content']=$row['content'];
                                        $h_data['content']= str_replace("高考早知道平台","福建高考信息平台",$h_data['content']);
                                        if ($row['h_type']==1){
                                            $e=explode('<p><img',$h_data['content']);
                                            $content2='';
                                            foreach($e as $k=>$v){
                                                if($k%5==0 && $k<>0){
                                                    $content2.='_ueditor_page_break_tag_<p>
                                                <img'.$e[$k];
                                                }else {
                                                    $content2 .= '<p>
                                            <img' . $e[$k];
                                                }
                                            }
                                            $h_data['content']=$content2;
                                        }
                                        Db::connect("database_art")->table("h_article_data")->insert($h_data);
                                    }
                                    if ($h_id){
                                        send_bd($row['id'],$h_id);
                                    }else{
                                        send_bd($row['id']);
                                    }
                                }
                                insert_today_nums(session('admin.id'));
                                if ($fit_channel['list_type']==2){
                                    school_article_num($row['school_id'],1);
                                    if ($fit_channel['p_type']==0){
                                        add_channel_nums(1,$row['school_id'],$row['channel_id'],$row['year'],1);
                                    }else {
                                        if ($values['province']=='1'){
//                                           return "省份选择错误";
                                            add_channel_nums('1',$row['school_id'],$row['channel_id'],$row['year'],1);

                                        }else{
                                            for ($i=0;$i<count($province);$i++){
                                                if ($province[$i]){
                                                    add_channel_nums($province[$i],$row['school_id'],$row['channel_id'],$row['year'],1);
                                                }
                                            }
                                        }
                                    }
                                }else{
                                    if ($row['h_type']==1){
                                        if (isset($row['adopt_id'])){
                                            DB::name('zd_user_archives')->where(['id'=>$row['adopt_id']])->update(['adopt_status'=>1,'archives_id'=>$row['id'],'adopt_time'=>time(),'m_id'=>session('admin.id')]);
                                        }
                                        if ($row['special_ids']){
                                            $special_ids=explode(",",$row['special_ids']);
                                            for ($i=0;$i<count($special_ids);$i++){
                                                if ($special_ids[$i]){
                                                    $special=DB::name('cms_special')
                                                        ->field("test_type,test_grade,test_year")
                                                        ->where(['id'=>$special_ids[$i]])
                                                        ->find();
                                                    if ($values['province']=='1'){
                                                        add_paper_nums(1,$row['channel_id'],$special['test_grade']?$special['test_grade']:3,$row['paper_subject_id'],$row['year'],1);
                                                    }else{
                                                        for ($i=0;$i<count($province);$i++){
                                                            if ($province[$i]){
                                                                add_paper_nums($province[$i],$row['channel_id'],$special['test_grade']?$special['test_grade']:3,$row['paper_subject_id'],$row['year'],2);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                }
//                                if (isset($row['zydm'])){
//                                    add_major($row['channel_id'],$row['zydm'],$row['year'],1);
//                                }
//                                $policy=DB::name('cms_channel')->field('parent_id')->where(['id'=>$fit_channel['parent_id']])->find();
//                                if ($policy['parent_id']==101){
                                    if (isset($row['policy_type'])){
                                       if ($row['policy_type']){
                                           for ($i=0;$i<count($province);$i++){
                                               if ($province[$i]){
                                                   add_policy_nums($row['channel_id'],$row['year'],$province[$i],$row['policy_type'],1);
                                               }
                                           }
                                       }
                                    }

//                                }
                            }elseif (strtolower(request()->action())=='edit'){
                                $article_id=Db::connect("database_art")->table("h_article")->field('id')->where(['zd_id'=>$row['id']])->find();
                                if ($article_id){
                                    $h_data['content']=$row['content'];
                                    $h_data['content']= str_replace("高考早知道平台","福建高考信息平台",$h_data['content']);
                                    if ($row['h_type']==1){
                                        $e=explode('<p><img',$h_data['content']);
                                        $content2='';
                                        foreach($e as $k=>$v){
                                            if($k%5==0 && $k<>0){
                                                $content2.='_ueditor_page_break_tag_<p>
                                        <img'.$e[$k];
                                            }else {
                                                $content2 .= '<p>
                                    <img' . $e[$k];
                                            }
                                        }
                                        $h_data['content']=$content2;
                                        Db::connect("database_art")->table("h_article")->where(['id'=>$article_id['id']])->update(['title'=>$row['title']]);
                                        Db::connect("database_art")->table("h_article_data")->where(['id'=>$article_id['id']])->update($h_data);
                                    }else{
                                        $province=explode(",",$values['province']);
                                        $isin = in_array("1",$province);
                                        $isin1 = in_array("3",$province);
                                        if ($isin || $isin1){
                                            Db::connect("database_art")->table("h_article")->where(['id'=>$article_id['id']])->update(['title'=>$row['title']]);
                                            Db::connect("database_art")->table("h_article_data")->where(['id'=>$article_id['id']])->update($h_data);
                                        }else{
                                            Db::connect("database_art")->table("h_article_data")->where(['id'=>$article_id['id']])->delete();
                                            Db::connect("database_art")->table("h_article")->where(['id'=>$article_id['id']])->delete();
                                        }
                                    }
                                }
                            }
                            if (strtolower(request()->action())=='edit'&& isset($values['province'])){
                                DB::name('cms_archives_province')->where(['archives_id'=>$row['id']])->delete();
                            }
                            if (strtolower(request()->action())=='edit'&& isset($row['special_ids'])){
                                DB::name('cms_archives_special')->where(['archives_id'=>$row['id']])->delete();
                            }
                            if (strtolower(request()->action())!='del'){
                                if ($row['special_ids']){
                                    $special_ids=explode(",",$row['special_ids']);
                                    for ($i=0;$i<count($special_ids);$i++){
                                        if ($special_ids[$i]){
                                            DB::name('cms_archives_special')->insert(['special_id'=>$special_ids[$i],'archives_id'=>$row['id']]);
                                        }
                                    }
                                }
                                if (empty($values['province'])){
                                    DB::name('cms_archives_province')->insert(['province_id'=>1,'archives_id'=>$row['id']]);
                                }else{
                                    $province=explode(",",$values['province']); //插入省份表
                                    for ($i=0;$i<count($province);$i++){
                                        if ($province[$i]){
                                            DB::name('cms_archives_province')->insert(['province_id'=>$province[$i],'archives_id'=>$row['id']]);
                                        }
                                    }

                                }
                                archivesInsertRedis($row['id']);
                            }
                        }
                    }
                }
                if (isset($row['tags'])) {
                    \addons\cms\model\Tag::refresh($row['tags'], $row['id']);
                }
                $changedData = $row->getChangedData();
                if (isset($changedData['status']) && $changedData['status'] == 'normal') {
                    //增加积分
                    User::score($config['score']['postarchives'], $row['user_id'], '发布文章');
                    //推送到熊掌号和百度站长
                    if ($config['baidupush']) {
                        $urls = [$row->fullurl];
                        \think\Hook::listen("baidupush", $urls);
                    }
                }
                if ($config['searchtype'] == 'xunsearch') {
                    //更新全文搜索
                    FulltextSearch::update($row->id);
                }
            });
            self::afterDelete(function ($row) use ($config) {
            $data = Archives::withTrashed()->find($row['id']);
            if ($data) {
                if ($row['status'] == 'normal') {
                    User::score(-$config['score']['postarchives'], $row['user_id'], '删除文章');
                }
                if ($config['searchtype'] == 'xunsearch') {
                    FulltextSearch::del($row);
                }
            } else {
                //删除相关TAG
                \addons\cms\model\Tag::refresh('', $row['id']);
            }
            //删除评论
            Comment::deleteByType('archives', $row['id'], !$data);
        });

    }

    public function getFlagList()
    {
        $config = get_addon_config('cms');
        return $config['flagtype'];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden'), 'rejected' => __('Status rejected'), 'pulloff' => __('Status pulloff')];
    }

    public function getStyleBoldAttr($value, $data)
    {
        return in_array('b', explode('|', $data['style']));
    }

    public function getStyleColorAttr($value, $data)
    {
        $result = preg_match("/(#([0-9a-z]{6}))/i", $data['style'], $matches);
        return $result ? $matches[1] : '';
    }

    public function getFlagTextAttr($value, $data)
    {
        $value = $value ? $value : $data['flag'];
        $valueArr = $value ? explode(',', $value) : [];
        $list = $this->getFlagList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getPublishtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['publishtime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPublishtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : ($value ? $value : null);
    }

    protected function setCreatetimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : ($value ? $value : null);
    }

    public static function getArrayData($data)
    {
        if (!isset($data['value'])) {
            $result = [];
            foreach ($data as $index => $datum) {
                $result['field'][$index] = $datum['key'];
                $result['value'][$index] = $datum['value'];
            }
            $data = $result;
        }
        $fieldarr = $valuearr = [];
        $field = isset($data['field']) ? $data['field'] : (isset($data['key']) ? $data['key'] : []);
        $value = isset($data['value']) ? $data['value'] : [];
        foreach ($field as $m => $n) {
            if ($n != '') {
                $fieldarr[] = $field[$m];
                $valuearr[] = $value[$m];
            }
        }
        return $fieldarr ? array_combine($fieldarr, $valuearr) : [];
    }

    public function channel()
    {
        return $this->belongsTo('Channel', 'channel_id', '', [], 'LEFT')->setEagerlyType(0);
    }

    public function special()
    {
        return $this->belongsTo('Special', 'special_id', '', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联模型
     */
    public function model()
    {
        return $this->belongsTo("Modelx", 'model_id')->setEagerlyType(1);
    }

    /**
     * 关联模型
     */
    public function user()
    {
        return $this->belongsTo("\\app\\common\\model\\User", 'user_id', 'id', [], 'LEFT')->setEagerlyType(1);
    }

    /**
     * 关联模型
     */
    public function admin()
    {
        return $this->belongsTo("\\app\\admin\\model\\CaAdmin", 'admin_id', 'id', [], 'LEFT')->setEagerlyType(1);
    }

    public function schools()
    {
        return $this->hasOne("\\app\\admin\\model\\Schoolz", 'id', 'school_id')->field('id,province,location,batch');
    }
}
